package de.mmis.core.base.ntp;

import java.io.IOException;
import java.net.UnknownHostException;

/**
 * This class starts a background thread for a periodic synchronization with a
 * NTP server. You can get the offset of the local clock against the NTP server
 * via the getOffset() function.
 * 
 * @author Daniel Moos
 */
public final class NTPSync extends Thread {

	static {
		offset = 0;
		instance = new NTPSync();
	}

	private static NTPClient ntp;
	@SuppressWarnings("unused")
	private static NTPSync instance;
	private static long offset;

	/**
	 * Get the offset of your local clock. Just add it to your current time.
	 * 
	 * @return the offset in ms
	 */
	public static long getOffset() {
		return offset;
	}

	private NTPSync() {
		super("NTP-sync-thread");
		setDaemon(true);

		try {
			// TODO: URL
			NTPSync.ntp = new NTPClient("ntp2.informatik.uni-rostock.de");
			NTPSync.offset = NTPSync.ntp.getOffset().longValue();
		} catch (UnknownHostException e) {
			throw new IllegalArgumentException(
					"The supplied NTP server is unreachable!", e);
		} catch (IOException e) {
			e.printStackTrace();
		}

		start();
	}

	@Override
	public void run() {
		while (true) {
			// sleep for 10 minutes
			try {
				Thread.sleep(600000l);
			} catch (InterruptedException e) {
				e.printStackTrace();
				return;
			}

			// update offset
			try {
				NTPSync.offset = NTPSync.ntp.getOffset().longValue();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
